package com.erp.database.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SerialNum {

	/**
	 * 生成编号的方式1
	 * @param dep 部门缩写 bm
	 * @param type 类型缩写 lx
	 * @param max 数据库查到的最大编号  bmlx2017011000001
	 * @return
	 */
	public static String serialNum(String dep, String type, String max) {
		String pattern = "yyyyMMdd";
		String today = dateToStr(pattern);
		String prefix = dep+type+today;
		if("".equals(max) || max == null){
			return prefix+String.format("%03d", 1);
		}else{
			return prefix+calPostFix(max,today);
		}
		
	}

	private static String calPostFix(String max,String today) {
		String regEx = "[^0-9]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(max);
		String str = m.replaceAll("").trim();
		String dbday = str.substring(0, 8);
		
		if (today.equals(dbday)) {
			long i = Long.parseLong(str.substring(8));
			return String.format("%03d", i + 1);
		}else{
			return String.format("%03d", 1);
		}
	}




	/**
	 * 生成编号的方式2
	 * @param max 数据库中的最大编号  bmlx2017011000001
	 * @return
	 */
	public static String serialNum(String max) {
		String pattern = "yyyyMMdd";
		String today = dateToStr(pattern);
		String str = max.replaceAll("[^a-zA-Z].+$", "");
		String num = max.replaceAll("[^0-9]","");
		String dbday = num.substring(0, 8);
		
		String prefix = str+today;
		
		if (today.equals(dbday)) {
			long i = Long.parseLong(str.substring(8));
			return prefix+String.format("%03d", i + 1);
		}else{
			return prefix+String.format("%03d", 1);
		}

	}
	
	
	public static String dateToStr(String pattern) {
		Date date = Calendar.getInstance().getTime();
		SimpleDateFormat format = null;
		if (pattern == null || "".equals(pattern)) {
			format = new SimpleDateFormat("yyyyMMdd");
		} else {
			format = new SimpleDateFormat(pattern);
		}
		return format.format(date);
	}


//	public static void main(String[] args) {
//		System.out.println(serialNum("zb", "ht", "zbht2017021500001"));//max为今天的
//		System.out.println(serialNum("zb", "ht", null));//max为空的测试
//		System.out.println(serialNum("zb", "ht", "zbht2017010900069"));//max为昨天的
//		
//		System.out.println("-----------------");
//		System.out.println(serialNum("zbht2017011000001"));//确认max有值的情况
//	}

}